import json
import os.path
import sys
import time
from tkinter import messagebox
import arrow
import requests
import pandas
from loguru import logger


class AppleStore:
    domain = "https://www.apple.com.cn"
    url_shop = "shop/fulfillment-messages"

    @classmethod
    def goods_option_14_pro8_16g_512g(cls):
        """
        丐中丐
        :return:
        """
        return "MKGP3CH/A"

    @classmethod
    def goods_option_14_pro_16g_1t(cls):
        """
        丐款
        :return:
        """
        return "MKGQ3CH/A"

    @classmethod
    def goods_option_16_pro_16g_512g(cls):
        return "MK183CH/A"

    @classmethod
    def goods_option_16_pro_16g_1t(cls):
        return "MK193CH/A"

    @classmethod
    def goods_option_16_max_32g_1t(cls):
        return "MK1A3CH/A"

    def __init__(self, province, city, region, goods_name):
        self.province = province
        self.city = city
        self.region = region
        self.goods_name = goods_name
        self.fast_start = 10
        self.fast_end = 13

    def get_url(self, path):
        return os.path.join(self.domain, path)

    def _goods_info(self, is_save=False):
        url = self.get_url(self.url_shop)
        params = {
            "parts.0": self.goods_name,
            "location": f"{self.province} {self.city} {self.region}",
            "mt": "regular",
            "_": int(arrow.now().timestamp() * 1000),
        }
        try:
            r = requests.get(url, params=params)
            self.r = r
            stores = r.json()["body"]["content"]["pickupMessage"]["stores"]
        except:
            logger.error("请求有误未获取到信息")
            return
        if is_save:
            with open("data.json", "w") as f:
                json.dump(r.json(), f, ensure_ascii=False)
        data = []
        for store in stores:
            address = store["address"]
            goods = store["partsAvailability"][self.goods_name]
            data.append({
                "name": address["address"],
                "address": address["address2"],
                "city": store["city"],
                "status": goods["pickupSearchQuote"],
                "describe": goods["storePickupQuote"]
            })
        self.goods_data = data
        return data

    def show_info(self):
        self._goods_info()
        df = pandas.DataFrame(self.goods_data)
        print(df)

    def timer_supervisor(self, interval: int, top: int = 3, interval_fast=60, exclude=None):
        while True:
            data = self._goods_info()
            if len(data) > top:
                data = data[:top]
            for item in data:
                # 过滤排除
                exclude_flag = False
                if exclude is not None:
                    for k in exclude:
                        if k in item and item[k] == exclude[k]:
                            exclude_flag = True
                            break
                if exclude_flag:
                    continue
                # 有货提示
                if item["status"] != "不可取货":
                    logger.info(item)
                    messagebox.showinfo("提示", item["describe"])
                    return
            logger.debug("暂无货物")
            now = arrow.now()
            hour = now.time().hour
            if self.fast_start <= hour <= self.fast_end:
                time.sleep(interval_fast)
            else:
                time.sleep(interval)


if __name__ == '__main__':
    ap = AppleStore("江苏", "南京", "雨花台区", AppleStore.goods_option_14_pro8_16g_512g())
    ap.timer_supervisor(10 * 60)
